﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Threading;
using CefSharp;
using DotNet.Utilities;
using YuanTu.Core.Log;

namespace CefApp
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public static CefSharp.Wpf.ChromiumWebBrowser webView;
        private static DispatcherTimer _timer = new DispatcherTimer();

        public MainWindow()
        {
            InitializeComponent();

            Logger.Main.Debug($"程序启动...");
            AutoExit();

            string url = "";
            string deviceid = "";
            if (ConfigurationManager.AppSettings["Url"] != null)
            {
                url = PathHelper.GetAbsPathFromPath(ConfigurationManager.AppSettings["Url"]);
            }
            else
            {
                MessageBox.Show("没有配置网页url");
                return;
            }
            if (ConfigurationManager .AppSettings["deviceid"] != null)
            {
                deviceid = ConfigurationManager .AppSettings["deviceid"];
            }
            else
            {
                MessageBox.Show("没有配置设备号deviceid");
                return;
            }

            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("CefSharp.BrowserSubprocess");
            foreach (Process process in processes)
            {
                process.Kill();
            }

            var setting = new CefSharp.Wpf.CefSettings();
            setting.CefCommandLineArgs.Add("enable-media-stream", "1");
            setting.CefCommandLineArgs.Add("enable-speech-output", "1");


            if (CefSharp.Cef.IsInitialized == false)
                CefSharp.Cef.Initialize(setting);

            webView = new CefSharp.Wpf.ChromiumWebBrowser();
            CefSharpSettings.LegacyJavascriptBindingEnabled = true;
            var bindScriptOption = new CefSharp.BindingOptions();
            bindScriptOption.CamelCaseJavascriptNames = false;

            webView.RegisterJsObject("BoundObject", new BoundObject(), bindScriptOption);
            web_grid.Children.Add(webView);

            if (!url.Contains("?"))
            {
                webView.Address = url + "?deviceid=" + deviceid;
            }
            else
            {
                webView.Address = url + "&deviceid=" + deviceid;
            }
        }

        /// <summary>
        /// 一定时间后自动关闭;
        /// </summary>
        private void AutoExit()
        {
            string autoStr = ConfigurationManager.AppSettings["AutoExit"];
            if (string.IsNullOrEmpty(autoStr))
            {
                autoStr = "0";
            }

            if(!int.TryParse(autoStr, out int autoValue))
            {
                autoValue = 0;
            }

            if (autoValue > 0)
            {
                Logger.Main.Debug($"程序将在{autoValue}分钟后自动退出.");
                _timer.Tick += TimerTick;
                _timer.Interval = TimeSpan.FromMinutes(autoValue);
                _timer.Start();
            }
        }

        private void TimerTick(object sender, EventArgs e)
        {
            _timer.Stop();
            ExitApp();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            double width = SystemParameters.PrimaryScreenWidth;
            double height = SystemParameters.PrimaryScreenHeight;
            this.Width = width;
            this.Height = height * (double)(8.5 / 10);
            this.Left = 0;
            this.Top = height * (double)(0.75 / 10);
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            webView.GetBrowser().CloseBrowser(true);
            Cef.Shutdown();
        }

        private void MainWindow_OnStateChanged(object sender, EventArgs e)
        {
            if ((sender as Window)?.WindowState == WindowState.Maximized)
            {
                if (ConfigurationManager.AppSettings["ReloadOnMax"] == "1")
                {
                    webView.GetBrowser()?.Reload(true);
                }
            }
        }

        public static void ExitApp()
        {
            Logger.Main.Debug($"程序即将退出...");
            webView.GetBrowser().CloseBrowser(true);
            Environment.Exit(0);
        }
    }

    public class BoundObject
    {
        [DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
        static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);

        public string DeviceId()
        {
            if (ConfigurationManager .AppSettings["deviceid"] != null)
            {
                return ConfigurationManager .AppSettings["deviceid"];
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 是否关闭：1-隐藏  2-关闭
        /// 用法：onclick="javascript:alert('1');BoundObject.CloseFlag('1');"
        /// </summary>
        public void CloseFlag(string flag)
        {
            if (flag == "1")
            {
                System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("CefApp");
                if (processes.Length >= 1)
                {
                    Console.WriteLine($"当前系统中有该程序在运行,将隐藏该程序");
                    //ShowWindow(processes[0].MainWindowHandle, 0); //隐藏;
                    ShowWindow(processes[0].MainWindowHandle, 6);   //最小化;
                }
            }
            else if (flag == "2")
            {
                MainWindow.ExitApp();
            }
        }
    }  

}
